package com.weixin.base.web;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;

import com.weixin.base.service.UserService;
import com.weixin.base.util.ExtJsPageHelper;
import com.weixin.base.util.ListRange;
import com.weixin.base.util.Tools;
import com.weixin.entity.BgUser;
import com.weixin.entity.TbWxUser;

@Controller
public class UserAction {

	@Autowired
	private UserService userService;

	/**
	 * 登录验证
	 */
	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {

		String result = "false";
		String sname = request.getParameter("sname");
		String spassword = request.getParameter("spassword");
		String randCode = request.getParameter("randCode");

		String randCodeSession = (String) request.getSession().getAttribute("randCode");

		if (randCodeSession == null || !randCodeSession.equalsIgnoreCase(randCode)) {// 验证码正确不区分大小写.
			result = "false2";
			response.getWriter().print(result);
			return;
		}
		spassword = Tools.EncoderByMd5(spassword);
		BgUser user = userService.login(sname, spassword);

		if (user != null) {
			request.getSession().setAttribute("userid", user.getNuserId());
			request.getSession().setAttribute("sAccount", user.getSaccount());
			request.getSession().setAttribute("nType", user.getNtype());
			request.getSession().setAttribute("sUserName", user.getSname());
			result = "true";
			System.out.println(user.getSname() + "登录：" + new Date());
		}

		response.getWriter().print(result);
	}

	/**
	 * 登录验证
	 */
	@RequestMapping(value = "/getImg.do")
	public void getImg(HttpServletRequest request, HttpServletResponse response) {
		Font mFont = new Font("Arial Black", Font.BOLD, 16);
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		// 指定图形验证码的大小
		int width = 80, height = 18;
		// 生成一张新图片
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		// 在图片中绘制内容
		Graphics g = image.getGraphics();
		Random random = new Random();
		g.setColor(getRandColor(200, 250));
		g.fillRect(1, 1, width - 1, height - 1);
		g.setColor(new Color(102, 102, 103));
		g.drawRect(0, 0, width - 1, height - 1);
		g.setFont(mFont);
		// 随机生成线条，让图片看起来更加杂乱
		g.setColor(getRandColor(160, 200));
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width - 1);
			int y = random.nextInt(height - 1);
			int x1 = random.nextInt(6) + 1;
			int y1 = random.nextInt(12) + 1;
			g.drawLine(x, y, x + x1, y + y1);
		}
		// 随机生成线条，让图片看起来更加杂乱
		for (int i = 0; i < 70; i++) {
			int x = random.nextInt(width - 1);
			int y = random.nextInt(height - 1);
			int x1 = random.nextInt(12) + 1;
			int y1 = random.nextInt(6) + 1;
			g.drawLine(x, y, x - x1, y - y1);
		}
		// 该变量用于保存系统生成的随机字符串
		String sRand = "";
		for (int i = 0; i < 4; i++) {
			// 取得一个随机字符
			String tmp = getRandomChar();
			sRand += tmp;
			// 将系统随机字符添加到图形验证码图片上
			g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
			g.drawString(tmp, 15 * i + 10, 15);
		}
		// 取得用户 Session
		HttpSession session = request.getSession();
		session.setMaxInactiveInterval(60 * 60);
		// 将生成的图形验证码添加到用户 Session 中
		session.setAttribute("randCode", sRand);
		g.dispose();
		// 输出图形验证码图片
		try {
			ImageIO.write(image, "JPEG", response.getOutputStream());
		} catch (IOException e) {
			// e.printStackTrace();
		}
	}

	// 生成随机的颜色
	public Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	// 生成随机字符的方法
	private String getRandomChar() {
		// int rand = (int) Math.round(Math.random() * 2);
		int rand = 3;// 全部生成数字随机码
		long itmp = 0;
		char ctmp = '\u0000';
		// 根据rand的值来决定是生成一个大写字母，小写字母和数字
		switch (rand) {
		// 生成大写字母的情形
		case 1:
			itmp = Math.round(Math.random() * 25 + 65);
			ctmp = (char) itmp;
			return String.valueOf(ctmp);
			// 生成小写字母的情形
		case 2:
			itmp = Math.round(Math.random() * 25 + 97);
			ctmp = (char) itmp;
			return String.valueOf(ctmp);
			// 生成数字的情形
		default:
			itmp = Math.round(Math.random() * 9);
			return String.valueOf(itmp);
		}
	}

	/**
	 * 查询用户菜单树
	 */
	@RequestMapping(value = "/module/main/menuData.do")
	public void menuData(HttpServletRequest request, HttpServletResponse response) {

		try {

			int userID = 0;

			if (request.getSession().getAttribute("userid") != null) {
				userID = Integer.parseInt(request.getSession().getAttribute("userid").toString());
			} else {
				response.getWriter().print("");
			}
			List<Map<String, Object>> result = userService.getNavTreeByUser(userID);

			ObjectMapper objectMapper = new ObjectMapper();

			String jsonResult = "";

			response.setCharacterEncoding("UTF-8");
			jsonResult = objectMapper.defaultPrettyPrintingWriter().writeValueAsString(IntoJson(result));
			response.getWriter().print(jsonResult);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 处理菜单树查询结果 结构为：{xxx:11,sss:22,children:{xx:11,ss:22}}
	 */
	private List<Map<String, Object>> IntoJson(List<Map<String, Object>> oDS) {
		Map<Integer, Map<String, Object>> rela = new HashMap<Integer, Map<String, Object>>();// 记录id对应的节点.
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();// 存放节点.
		try {
			for (Map<String, Object> map : oDS) {
				int nNavTreeId = Integer.parseInt(map.get("nNavTreeId").toString());
				int nPId = Integer.parseInt(map.get("nPId").toString());
				String sName = map.get("sName") == null ? "" : map.get("sName").toString();
				String sUrl = map.get("sUrl") == null ? "" : map.get("sUrl").toString();
				HashMap<String, Object> node = new HashMap<String, Object>();
				node.put("url", sUrl);
				node.put("id", String.valueOf(nNavTreeId));
				node.put("pid", String.valueOf(nPId));
				node.put("text", sName);
				if (nPId == 0) {// 根节点
					node.put("id", "root");
					list.add(node);
				} else {
					// 得到父节点
					Map<String, Object> pNode = rela.get(nPId);
					// 没有找到对应的父节点.
					if (pNode == null) {
						continue;
					}
					// 子节点集合
					List<Map<String, Object>> listChild = null;
					// 如果父节点包含children 则取出子节点集合 否则创建集合再放入父节点
					if (pNode.containsKey("children")) {
						listChild = (List<Map<String, Object>>) pNode.get("children");
					} else {
						listChild = new ArrayList<Map<String, Object>>();
						pNode.put("children", listChild);
					}
					// 用于显示父节点状态:leaf:false表明可以展开。 并展开节点：
					pNode.put("leaf", false);
					pNode.put("expanded", true);
					listChild.add(node);
				}
				// 将所有节点存入map 用于找到设置叶子节点
				rela.put(nNavTreeId, node);
			}

			Set<Integer> set = rela.keySet();
			Iterator<Integer> iterator = set.iterator();
			while (iterator.hasNext()) {
				int it = iterator.next();
				if (rela.get(it) != null) {
					// map中没找到leaf值 则设置为叶子节点
					if (!rela.get(it).containsKey("leaf")) {
						rela.get(it).put("leaf", true);
					}
				}
			}

		} catch (Exception oException) {
			oException.printStackTrace();
		}
		return list;
	}

	/**
	 * 返回菜单树右边功能页面 :角色管理
	 */
	@RequestMapping("/module/main/menuRoleManager.do")
	public String menuRoleManager(HttpServletRequest request, HttpServletResponse response) {

		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "menuRoleManager.do");
		request.setAttribute("iswrite", iswrite);
		return "/manager/role";
	}

	/**
	 * 返回菜单树右边功能页面 用户管理
	 */
	@RequestMapping("/module/main/menuUserManager.do")
	public String menuUserManager(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "menuUserManager.do");
		request.setAttribute("iswrite", iswrite);
		return "/manager/user";
	}

	/**
	 * 返回菜单树右边功能页面：修改密码
	 */
	@RequestMapping("/module/main/menuUpdatePwd.do")
	public String menuUpdatePwd(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "menuUpdatePwd.do");
		request.setAttribute("iswrite", iswrite);
		return "/manager/upPwd";
	}

	/**
	 * 返回菜单树右边功能页面：通道公共属性设置
	 */
	@RequestMapping("/module/main/updateFilePoolPublicSet.do")
	public String updateFilePoolPublicSet(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "updateFilePoolPublicSet.do");
		request.setAttribute("iswrite", iswrite);
		return "/updateFile/updateFilePoolPublicSet";
	}

	/**
	 * 返回菜单树右边功能页面：归属地管理 短信中心号
	 */
	@RequestMapping("/module/main/areaCenter.do")
	public String areaCenterManager(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "areaCenter.do");
		request.setAttribute("iswrite", iswrite);
		return "/area/areaCenter";
	}

	/**
	 * 返回菜单树右边功能页面：归属地管理 手机号码段
	 */
	@RequestMapping("/module/main/areaMoblie.do")
	public String areaMoblieManager(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "areaMoblie.do");
		request.setAttribute("iswrite", iswrite);
		return "/area/areaMoblie";
	}

	/**
	 * 返回菜单树右边功能页面：地市管理
	 */
	@RequestMapping("/module/main/areaManager.do")
	public String areaManager(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "areaManager.do");
		request.setAttribute("iswrite", iswrite);
		return "/area/areaManager";
	}

	/**
	 * 修改密码
	 */
	@RequestMapping("/module/main/updatePwd.do")
	public void updatePwd(HttpServletRequest request, HttpServletResponse response) throws IOException {

		String sAccount = request.getParameter("sAccount");
		String lpwd = request.getParameter("lpwd");
		String lpwdmd5 = Tools.EncoderByMd5(lpwd);
		String qpwd = request.getParameter("qpwd");
		String lqpwdmd5 = Tools.EncoderByMd5(qpwd);
		String result = "";

		try {

			if (userService.getByLogin(sAccount, lpwdmd5) == null) {
				result = "-1";
			} else {
				userService.updatePwd(sAccount, lqpwdmd5);
				result = "1";
			}
		} catch (Exception e) {
			result = "0";
			e.printStackTrace();
		}
		response.getWriter().print(result);

	}

	/**
	 * 分页用户查询
	 */
	@RequestMapping(value = "/module/main/searchUser.do")
	public void searchUser(HttpServletRequest request, HttpServletResponse response) throws IOException {

		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, null);
		Page page = userService.findUserByPage(pr);

		List<BgUser> TbBgUserlist = (List) page.getResult();
		ListRange<BgUser> resultList = new ListRange<BgUser>();
		resultList.setList(TbBgUserlist);
		resultList.setTotalSize(page.getTotalCount());
		resultList.setSumTotal(page.getSumTotal());
		resultList.setPageSize(page.getPageSize());
		resultList.setPagecount(page.getLastPageNumber());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		response.getWriter().print(new ObjectMapper().defaultPrettyPrintingWriter().writeValueAsString(resultList));
	}

	/**
	 * 添加用户
	 */
	@RequestMapping(value = "/module/main/saveUser.do")
	public void saveUser(HttpServletRequest request, HttpServletResponse response) throws IOException {

		String result = "";
		try {

			BgUser user = new BgUser();

			user.setSaccount(request.getParameter("sAccount"));
			user.setSpassword(request.getParameter("sPassword"));
			user.setSname(request.getParameter("sName"));
			user.setNtype(Integer.parseInt(request.getParameter("nType")));
			user.setNsex(Integer.parseInt(request.getParameter("nSex")));
			user.setSqq(request.getParameter("sQQ"));
			user.setSemail(request.getParameter("sEmail"));
			user.setSmobile(request.getParameter("sMobile"));
			user.setStel(request.getParameter("sTel"));
			user.setSfax(request.getParameter("sFax"));
			user.setSzip(request.getParameter("sZip"));
			user.setSaddress(request.getParameter("sAddress"));
			user.setSbrief(request.getParameter("sBrief"));
			user.setNisValid(Integer.parseInt(request.getParameter("nisValid")));

			if (userService.isExit(user) == 1) {
				result = "-1";
			} else {
				String sPass = Tools.EncoderByMd5(user.getSpassword());
				user.setSpassword(sPass);
				userService.save(user);
				result = "1";
			}
		} catch (Exception e) {
			result = "0";
			e.printStackTrace();
		}
		response.getWriter().print(result);
	}

	/**
	 * 查询用户角色
	 */
	@RequestMapping(value = "/module/main/selectUserRelRight.do")
	public void selectUserRelRight(HttpServletRequest request, HttpServletResponse response) throws IOException {

		String result = "";
		try {
			int nuserId = Integer.parseInt(request.getParameter("nuserId"));
			Map<String, Object> map = userService.selectUserRelRight(nuserId);

			List<Map<String, Object>> nRightAll = (List<Map<String, Object>>) map.get("nRightAll");
			List<Map<String, Object>> nUserRight = (List<Map<String, Object>>) map.get("nUserRight");

			for (int i = 0; i < nRightAll.size(); i++) {
				Map<String, Object> rightallmap = nRightAll.get(i);
				for (int j = 0; j < nUserRight.size(); j++) {
					Map<String, Object> userrightmap = nUserRight.get(j);
					if (rightallmap.get("nRightId").equals(userrightmap.get("nRightId"))) {
						rightallmap.put("checked", true);
					}
				}
			}
			result = new ObjectMapper().defaultPrettyPrintingWriter().writeValueAsString(nRightAll);
		} catch (Exception e) {
			e.printStackTrace();
		}
		response.getWriter().print(result);
	}

	/**
	 * 用户分配角色
	 */
	@RequestMapping(value = "/module/main/saveUserRelRight.do")
	public void saveUserRelRight(HttpServletRequest request, HttpServletResponse response) throws IOException {

		String result = "";
		try {
			String sRoles = request.getParameter("sRoles");
			int nuserId = Integer.parseInt(request.getParameter("nuserId"));
			userService.saveUserRelRight(sRoles, nuserId);
			result = "1";
		} catch (Exception e) {
			result = "0";
			e.printStackTrace();
		}
		response.getWriter().print(result);
	}

	/**
	 * 修改用户
	 */
	@RequestMapping(value = "/module/main/upUser.do")
	public void upUser(HttpServletRequest request, HttpServletResponse response) throws IOException {

		String result = "";
		try {
			BgUser user = new BgUser();

			user.setSaccount(request.getParameter("sAccount"));
			user.setSpassword(request.getParameter("spassword").toString().trim());
			user.setSname(request.getParameter("sName"));
			user.setNtype(Integer.parseInt(request.getParameter("nType")));
			user.setNsex(Integer.parseInt(request.getParameter("nSex")));
			user.setSqq(request.getParameter("sQQ"));
			user.setSemail(request.getParameter("sEmail"));
			user.setSmobile(request.getParameter("sMobile"));
			user.setStel(request.getParameter("sTel"));
			user.setSfax(request.getParameter("sFax"));
			user.setSzip(request.getParameter("sZip"));
			user.setSaddress(request.getParameter("sAddress"));
			user.setSbrief(request.getParameter("sBrief"));
			user.setNisValid(Integer.parseInt(request.getParameter("nisValid")));
			user.setNuserId(Integer.parseInt(request.getParameter("nuserId")));

			if (userService.isExit2(user) == 1) {
				result = "-1";
			} else {
				userService.update(user);
				result = "1";
			}
		} catch (Exception e) {
			result = "0";
			e.printStackTrace();
		}
		response.getWriter().print(result);
	}

	/**
	 * 删除用户
	 */
	@RequestMapping(value = "/module/main/delUser.do")
	public void delUser(HttpServletRequest request, HttpServletResponse response) throws IOException {

		String ids = request.getParameter("ids");
		String[] idarray = ids.split(",");
		String result = "";
		try {
			for (int i = 0; i < idarray.length; i++) {
				java.lang.Integer id = new java.lang.Integer((String) idarray[i]);
				userService.deleteById(id);
			}
			result = "1";
		} catch (Exception e) {
			result = "0";
			e.printStackTrace();
		}
		response.getWriter().print(result);
	}

	/**
	 * 监控服务器链接 与数据库访问链接
	 */
	@RequestMapping(value = "/monitor/monitorserversql.do")
	public void monitorserversql(HttpServletRequest request, HttpServletResponse response) throws IOException {

		int result = 0;
		try {

			result = userService.monitorserversql();
		} catch (Exception e) {
			result = 0;
			e.printStackTrace();
		}
		response.getWriter().print(result);
	}

	/**
	 * 查询所有厂家用户
	 */
	@RequestMapping(value = "/module/main/selectFactoryUser.do")
	public void selectFactoryUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Map<String, Object>> userlist = userService.getUserListbytype(3);
		ObjectMapper objm = new ObjectMapper();
		String result = objm.defaultPrettyPrintingWriter().writeValueAsString(userlist);
		response.getWriter().print(result);
	}

	/**
	 * 查询所有商务人员
	 */
	@RequestMapping(value = "/module/main/selectSalesUser.do")
	public void selectSalesUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Map<String, Object>> userlist = userService.getUserListbytype(2);
		ObjectMapper objm = new ObjectMapper();
		String result = objm.defaultPrettyPrintingWriter().writeValueAsString(userlist);
		response.getWriter().print(result);
	}

	/**
	 * 查询所有运营人员
	 */
	@RequestMapping(value = "/module/main/selectBusinessUser.do")
	public void selectBusinessUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Map<String, Object>> userlist = userService.getUserListbytype(5);
		ObjectMapper objm = new ObjectMapper();
		String result = objm.defaultPrettyPrintingWriter().writeValueAsString(userlist);
		response.getWriter().print(result);
	}

	/**
	 * 返回菜单树右边功能页面：关注回复
	 */
	@RequestMapping("/module/main/replyNotice.do")
	public String replyNotice(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "replyNotice.do");
		request.setAttribute("iswrite", iswrite);
		return "/tpreply/replyNotice";
	}

	/**
	 * 返回菜单树右边功能页面：自动回复
	 */
	@RequestMapping("/module/main/replyAuto.do")
	public String replyAuto(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "replyAuto.do");
		request.setAttribute("iswrite", iswrite);
		return "/tpreply/replyAuto";
	}
	
	/**
	 * 返回菜单树右边功能页面：自定义菜单回复
	 */
	@RequestMapping("/module/main/replyCustomMenu.do")
	public String replyCustomMenu(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "replyCustomMenu.do");
		request.setAttribute("iswrite", iswrite);
		return "/tpreply/replyCustomMenu";
	}

	/**
	 * 返回菜单树右边功能页面：首页模版设置
	 */
	@RequestMapping("/module/main/siteTemplate.do")
	public String siteTemplate(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "siteTemplate.do");
		request.setAttribute("iswrite", iswrite);
		return "/tpsite/siteTemplate";
	}

	/**
	 * 返回菜单树右边功能页面：首页菜单设置
	 */
	@RequestMapping("/module/main/siteMenu.do")
	public String siteMenu(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "siteMenu.do");
		request.setAttribute("iswrite", iswrite);
		return "/tpsite/siteMenu";
	}

	/**
	 * 返回菜单树右边功能页面：文章管理
	 */
	@RequestMapping("/module/main/siteText.do")
	public String siteText(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "siteText.do");
		request.setAttribute("iswrite", iswrite);
		return "/tpsite/siteText";
	}
	
	/**
	 * 返回菜单树右边功能页面：自定义菜单
	 */
	@RequestMapping("/module/main/siteCustomMenu.do")
	public String siteCustomMenu(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "siteCustomMenu.do");
		request.setAttribute("iswrite", iswrite);
		return "/tpsite/siteCustomMenu";
	}
	
	/**
	 * 返回菜单树右边功能页面：微信号信息设置
	 */
	@RequestMapping("/module/main/wxUser.do")
	public String wxUserSet(HttpServletRequest request, HttpServletResponse response) {
		int nuserId = Integer.parseInt(request.getParameter("userid"));
		int iswrite = userService.selectIsWrite(nuserId, "wxUser.do");

		TbWxUser tbWxUser = userService.selectWxUser(nuserId);
		request.setAttribute("iswrite", iswrite);
		request.setAttribute("ntype", tbWxUser.getNtype());
		request.setAttribute("nUserId", nuserId);
		request.setAttribute("nWxUserId", tbWxUser.getNWxUserId());
		request.setAttribute("sAppID", tbWxUser.getSAppID());
		request.setAttribute("sAppSecret", tbWxUser.getSAppSecret());
		request.setAttribute("sDeveloperURL", tbWxUser.getSDeveloperURL());
		request.setAttribute("sName", tbWxUser.getSName());
		request.setAttribute("sToken", tbWxUser.getSToken());
		request.setAttribute("sWxAccount", tbWxUser.getSWxAccount());
		request.setAttribute("sRemark", tbWxUser.getSRemark());
		return "/manager/wxUser";
	}

	/**
	 * 修改微信号信息设置
	 */
	@RequestMapping("/module/main/upWxUser.do")
	public void upWxUser(HttpServletRequest request, HttpServletResponse response) throws IOException {

		TbWxUser tbWxUser = new TbWxUser();
		tbWxUser.setNUserId(Tools.convertRi(request.getParameter("nUserId")));
		tbWxUser.setNWxUserId(Tools.convertRi(request.getParameter("nWxUserId")));

		tbWxUser.setNtype(Tools.convertRi(request.getParameter("ntype")));
		tbWxUser.setSAppID(Tools.convertRs(request.getParameter("sAppID")));
		tbWxUser.setSAppSecret(Tools.convertRs(request.getParameter("sAppSecret")));
		tbWxUser.setSDeveloperURL(Tools.convertRs(request.getParameter("sDeveloperURL")));
		tbWxUser.setSName(Tools.convertRs(request.getParameter("sName")));
		tbWxUser.setSRemark(Tools.convertRs(request.getParameter("sRemark")));
		tbWxUser.setSToken(Tools.convertRs(request.getParameter("sToken")));
		tbWxUser.setSWxAccount(Tools.convertRs(request.getParameter("sWxAccount")));

		int result = 0;

		try {
			if (tbWxUser.getNWxUserId() <= 0) {
				result = userService.addWxUser(tbWxUser);
			} else {
				result = userService.upWxUser(tbWxUser);
			}
		} catch (Exception e) {
			result = -1;
			e.printStackTrace();
		}
		response.getWriter().print(result > 0 ? "1" : "-1");
	}
	
	/**
	 * admin--------------------------------------------------------------------
	 */
	/**
	 * 返回菜单树右边功能页面：关注回复
	 */
	@RequestMapping("/module/main/adminReplyNotice.do")
	public String adminReplyNotice(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "adminReplyNotice.do");
		request.setAttribute("iswrite", iswrite);
		return "/adminreply/replyNotice";
	}

	/**
	 * 返回菜单树右边功能页面：自动回复
	 */
	@RequestMapping("/module/main/adminReplyAuto.do")
	public String adminReplyAuto(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "adminReplyAuto.do");
		request.setAttribute("iswrite", iswrite);
		return "/adminreply/replyAuto";
	}
	
	/**
	 * 返回菜单树右边功能页面：自定义菜单回复
	 */
	@RequestMapping("/module/main/adminReplyCustomMenu.do")
	public String adminReplyCustomMenu(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "adminReplyCustomMenu.do");
		request.setAttribute("iswrite", iswrite);
		return "/adminreply/replyCustomMenu";
	}

	/**
	 * 返回菜单树右边功能页面：首页模版设置
	 */
	@RequestMapping("/module/main/adminSiteTemplate.do")
	public String adminSiteTemplate(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "adminSiteTemplate.do");
		request.setAttribute("iswrite", iswrite);
		return "/adminsite/siteTemplate";
	}

	/**
	 * 返回菜单树右边功能页面：首页菜单设置
	 */
	@RequestMapping("/module/main/adminSiteMenu.do")
	public String adminSiteMenu(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "adminSiteMenu.do");
		request.setAttribute("iswrite", iswrite);
		return "/adminsite/siteMenu";
	}

	/**
	 * 返回菜单树右边功能页面：文章管理
	 */
	@RequestMapping("/module/main/adminSiteText.do")
	public String adminSiteText(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "adminSiteText.do");
		request.setAttribute("iswrite", iswrite);
		return "/adminsite/siteText";
	}
	
	/**
	 * 返回菜单树右边功能页面：自定义菜单
	 */
	@RequestMapping("/module/main/adminSiteCustomMenu.do")
	public String adminSiteCustomMenu(HttpServletRequest request, HttpServletResponse response) {
		int iswrite = userService.selectIsWrite(Integer.parseInt(request.getParameter("userid")), "adminSiteCustomMenu.do");
		request.setAttribute("iswrite", iswrite);
		return "/adminsite/siteCustomMenu";
	}
	
	/**
	 * 返回菜单树右边功能页面：微信号信息设置
	 */
	@RequestMapping("/module/main/adminwxUser.do")
	public String adminwxUserSet(HttpServletRequest request, HttpServletResponse response) {
		int nuserId = Integer.parseInt(request.getParameter("userid"));
		int iswrite = userService.selectIsWrite(nuserId, "adminwxUser.do");

//		TbWxUser tbWxUser = userService.selectWxUser(nuserId);
		request.setAttribute("iswrite", iswrite);
//		request.setAttribute("ntype", tbWxUser.getNtype());
//		request.setAttribute("nUserId", nuserId);
//		request.setAttribute("nWxUserId", tbWxUser.getNWxUserId());
//		request.setAttribute("sAppID", tbWxUser.getSAppID());
//		request.setAttribute("sAppSecret", tbWxUser.getSAppSecret());
//		request.setAttribute("sDeveloperURL", tbWxUser.getSDeveloperURL());
//		request.setAttribute("sName", tbWxUser.getSName());
//		request.setAttribute("sToken", tbWxUser.getSToken());
//		request.setAttribute("sWxAccount", tbWxUser.getSWxAccount());
//		request.setAttribute("sRemark", tbWxUser.getSRemark());
		return "/manager/adminwxUser";
	}
	
	/**
	 * 返回菜单树右边功能页面：微信号信息设置
	 */
	@RequestMapping("/module/main/adminSelectWxUser.do")
	public void adminSelectWxUser(HttpServletRequest request, HttpServletResponse response)throws IOException {
		int nuserId = Tools.convertRi(request.getParameter("userid"));

		TbWxUser tbWxUser = userService.selectWxUser(nuserId);
		ObjectMapper objm = new ObjectMapper();
		String result = objm.defaultPrettyPrintingWriter().writeValueAsString(tbWxUser);
		response.getWriter().print(result);
	}

	/**
	 * 修改微信号信息设置
	 */
	@RequestMapping("/module/main/adminUpWxUser.do")
	public void adminUpWxUser(HttpServletRequest request, HttpServletResponse response) throws IOException {

		TbWxUser tbWxUser = new TbWxUser();
		tbWxUser.setNUserId(Tools.convertRi(request.getParameter("nUserId")));
		tbWxUser.setNWxUserId(Tools.convertRi(request.getParameter("nWxUserId")));

		tbWxUser.setNtype(Tools.convertRi(request.getParameter("ntype")));
		tbWxUser.setSAppID(Tools.convertRs(request.getParameter("sAppID")));
		tbWxUser.setSAppSecret(Tools.convertRs(request.getParameter("sAppSecret")));
		tbWxUser.setSDeveloperURL(Tools.convertRs(request.getParameter("sDeveloperURL")));
		tbWxUser.setSName(Tools.convertRs(request.getParameter("sName")));
		tbWxUser.setSRemark(Tools.convertRs(request.getParameter("sRemark")));
		tbWxUser.setSToken(Tools.convertRs(request.getParameter("sToken")));
		tbWxUser.setSWxAccount(Tools.convertRs(request.getParameter("sWxAccount")));

		int result = 0;

		try {
			if (tbWxUser.getNUserId() <= 0) {
				result = -1;
			} 
			else if (tbWxUser.getNWxUserId() <= 0) {
				result = userService.addWxUser(tbWxUser);
			} else {
				result = userService.upWxUser(tbWxUser);
			}
		} catch (Exception e) {
			result = -1;
			e.printStackTrace();
		}
		response.getWriter().print(result > 0 ? "1" : "-1");
	}

}